package com.itheima.springbootmybatisdemo.filter;

import com.itheima.springbootmybatisdemo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 过滤器
 *
 * @Author mr.luo
 * @Date 15 4月 2025 16:19
 */
@WebFilter(urlPatterns = "/*")
@Slf4j
public class WebFilterDemo1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器开始工作");
        //释放资源
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("请求的资源为：{}", requestURI);
        if ("/login".equals(requestURI)) {
            log.info("登录请求,直接放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("token");
        log.info("获取到token为: {}", token);
        if (!StringUtils.hasLength(token)) {
            log.info("获取到token为空,返回错误结果401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //解析token
        try {
            Claims claims = JwtUtils.parseToken(token);
            log.info("解析到当前用户id为: {}", claims.get("id"));
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            log.error("解析token失败", e);
            return;
        }
    }

    @Override
    public void destroy() {
        log.info("销毁释放资源");
    }
}
